<?php

require_once('inc.php');

class CliLouncher
{
    protected $controller;
    protected $action;
    protected $params;

    protected $color_codes = [
        'red' => 31,
        'blue' => 34,
    ];

    protected function init()
    {
        $opts = getopt('c:p::');
        if (!empty($opts['c'])) {
            list($this->controller, $this->action) = explode('.', $opts['c']);
        }
        if (!empty($opts['p'])) {
            $this->params = $opts['p'];
        }

        if (empty($this->controller) || empty($this->action)) {
            throw new SSTException('Wrong params; expected "-c=ControllerName.ActionName"');
        }
    }

    protected function colorString($str, $color)
    {
        return $str = "\033[" . $this->color_codes[$color] . "m" . $str . "\033[0m";
    }

    protected function outError($str)
    {
        $str = $this->colorString('ERROR: ' . $str, 'red');
        $this->out($str);
    }

    protected function out($str)
    {
        echo $str . PHP_EOL;
    }

    public function run()
    {
        try {
            $this->init();

            Autoloader::load($this->controller);
            $inst = new $this->controller;

            if (method_exists($inst, $this->action)) {
                $inst->{$this->action}($this->params);
            } else {
                throw new SSTException('Action doesn\'t exists: ' . $this->controller . '->' . $this->action);
            }
        } catch(Exception $e) {
            $this->outError($e->getMessage());
        }
    }
}

$CliLouncher = new CliLouncher();
$CliLouncher->run();